from io import BytesIO
from pprint import pprint
from django.core.exceptions import ValidationError
from django.shortcuts import render,redirect,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from web import models
from web.utils.bootstrap import BootstrapModelForm,BootstrapForm
import datetime
import random
from web.models import GameTokens,Out_GameTokens
from web.models import PhoneCharge,Out_PhoneCharge
from web.models import UserInfo,Data
from django import forms
# Create your views here.
from django.http import HttpResponseForbidden, JsonResponse
from django.db.models import Q
from django.db.models import Sum
from web.utils.self_func import phone_data_out,phone_data_reout,game_data_out,game_data_reout
from web.utils.code import check_code
from web.models import Discount


def generate_order_id():
    # 获取当前日期
    date_str = datetime.datetime.now().strftime('%Y%m%d')
    # 生成一个随机数（可选范围）
    unique_id = random.randint(1000, 9999)
    # 拼接日期和随机数
    return f"{date_str}{unique_id}"

def notice(request):
    # info = request.session.get('info')
    # print(info)
    #查询当前的话费和点券折扣
    if request.user.usertype == 1:
        all_discount = models.Discount.objects.all()
        context = {
            'all_discount':all_discount,
        }

    #如果是管理员，直接查询其设置的折扣
    if request.user.usertype == 2:
        current_phone_discount_for_consumer = models.Discount.objects.filter(name=request.user.name).first().phone_discount_for_consumer
        current_game_discount_for_consumer = models.Discount.objects.filter(name=request.user.name).first().game_discount_for_consumer
        current_phone_discount_for_vendor = models.Discount.objects.filter(name=request.user.name).first().phone_discount_for_vendor
        current_game_discount_for_vendor = models.Discount.objects.filter(name=request.user.name).first().game_discount_for_vendor

        context = {
            'current_phone_discount_for_consumer': current_phone_discount_for_consumer,
            'current_game_discount_for_consumer': current_game_discount_for_consumer,
            'current_phone_discount_for_vendor': current_phone_discount_for_vendor,
            'current_game_discount_for_vendor': current_game_discount_for_vendor,
        }
    #如果是消费者，查询创建他的管理员账号，然后再查询其管理员为消费者设置的对应折扣
    if request.user.usertype  == 3:
        user_create_person = models.UserInfo.objects.filter(name=request.user.name).first().create_person
        current_phone_discount_for_consumer = models.Discount.objects.filter(name=user_create_person).first().phone_discount_for_consumer
        current_game_discount_for_consumer = models.Discount.objects.filter(name=user_create_person).first().game_discount_for_consumer
        context = {
            'current_phone_discount_for_consumer': current_phone_discount_for_consumer,
            'current_game_discount_for_consumer': current_game_discount_for_consumer,
        }
    #如果是供应商,查询创建他的管理员账号，然后再查询管理员为供应商设置的对应折扣，
    if request.user.usertype  == 4:
        user_create_person = models.UserInfo.objects.filter(name=request.user.name).first().create_person
        current_phone_discount_for_vendor = models.Discount.objects.filter(name=user_create_person).first().phone_discount_for_vendor
        current_game_discount_for_vendor = models.Discount.objects.filter(name=user_create_person).first().game_discount_for_vendor
        context = {

            'current_phone_discount_for_vendor': current_phone_discount_for_vendor,
            'current_game_discount_for_vendor': current_game_discount_for_vendor,
        }

    if request.user.usertype == 5:
        context = {

        }



    return render(request,'notice.html',context)

class LoginForm(BootstrapForm):
    name = forms.CharField(
        label='用户名',
        widget=forms.TextInput
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True)
    )

    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request,'login.html',{'form':form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        #获取用户在表单中提交的验证码
        user_input_code = form.cleaned_data.pop('code')
        #获取视图函数生成的验证码
        code = request.session.get('image_code','')

        if code.strip().upper() != user_input_code.strip().upper():
            form.add_error('code','验证码错误')
            return render(request, 'login.html', {'form': form})

        print('form.cleaned_data的数据：',form.cleaned_data)
        user_object = models.UserInfo.objects.filter(**form.cleaned_data).first()
        if not user_object:
            form.add_error("password","用户名或密码错误")
            return render(request, 'login.html', {'form': form})

        #用户名和密码正确
        #网站生成随机字符串；写到用户浏览器的cookie中；再写入到session中；
        request.session['info'] = {'id':user_object.id,'name':user_object.name}
        #用户session信息保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/notice/')
    return render(request,'login.html',{'form':form})


def image_code(request):
    img,code_string = check_code()
    print(code_string)
    #写入到自己的session中（以便于后续获取验证码进行校验）
    request.session['image_code'] = code_string
    #给session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream,'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.clear()
    return redirect('/login/')

def game_list(request):
    if request.user.usertype in [1,2,4,5]:
        queryset = models.GameTokens.objects.all()
        print(queryset)
    if request.user.usertype == 3:
        queryset = models.GameTokens.objects.filter(consumer=request.user.name)
        print(queryset)


    return render(request,'game_list.html',{'queryset':queryset})


class GameModeForm(BootstrapModelForm):

    class Meta:
        model = models.GameTokens
        fields = ["game_name","denomination","charge_link","consumer"]


def game_add(request):

    title = "添加点券订单"

    if request.method == 'GET':
        form = GameModeForm()
        if request.user.usertype == 3:  # 消费者的用户类型标识为 3
            form.fields.pop('consumer')

        context = {
            'form':form,
            'title':title
        }

        return render(request,'game_add.html',context)

    form = GameModeForm(data=request.POST)
    if request.user.usertype == 3:  # 如果用户是消费者，删除 consumer 字段以避免非法提交
        form.fields.pop('consumer')


    if form.is_valid():
        # create_person = request.session['info']['name']
        form.instance.in_storage_person = request.user.name
        form.instance.order_number = generate_order_id()
        if request.user.usertype == 3:  # 消费者的用户类型标识为 3
            form.instance.consumer = request.user.name
            form.instance.name = request.user.name
        else:
            form.instance.name = form.cleaned_data['consumer']
            print('xx',form.cleaned_data['consumer'])
        form.save()
        return redirect('/game/list/')

    return render(request,'game_add.html',{'form':form})



def game_edit(request,uid):
    title = '编辑点券订单'
    row_object = models.GameTokens.objects.filter(id=uid).first()
    if request.method == 'GET':
        form = GameModeForm(instance=row_object)
        context = {
            'form': form,
            'title': title
        }
        return render(request,'game_add.html',context)

    form = GameModeForm(data=request.POST,instance=row_object)
    form.save()
    return redirect('/game/list/')


def game_delete(request,uid):
    models.GameTokens.objects.filter(id=uid).delete()
    return redirect('/game/list/')



def game_out(request,uid):
    """将 GameTokens 的记录快速转存到 Out_GameTokens"""
    # 获取原始数据
    game_token = GameTokens.objects.get(id=uid)
    print(game_token)
    print('game_token.name:',game_token.name)

    # 创建新的 Out_GameTokens 实例并保存
    out_game_token = Out_GameTokens(
        name = game_token.name,
        game_name=game_token.game_name,
        denomination=game_token.denomination,
        charge_link=game_token.charge_link,
        order_create_time=game_token.order_create_time,
        order_number=game_token.order_number,
        consumer=game_token.consumer,
        in_storage_person=game_token.in_storage_person,
        order_finish_time=datetime.datetime.now().date(),  # 当前时间
        order_status=1,  # 默认状态：已支付
        out_storage_person=request.user.name,  # 点击出库的人
    )
    out_game_token.save()
    game_token.delete()

    # 将消费者的账户余额更新
    if request.user.usertype == 2:
        #获取当前管理员所设置的对消费者设置的游戏点券的折扣系数
        game_discount_for_consumer = models.Discount.objects.filter(name=request.user.name).first().game_discount_for_consumer

    if request.user.usertype in [4, 5]:
        #先获取当前的供货商或者客服所对应的直属管理员
        creater_user = models.UserInfo.objects.filter(name=request.user.name).first().create_person
        #获取其直属管理员所设置的游戏点券的折扣系数
        game_discount_for_consumer = models.Discount.objects.filter(name=creater_user).first().game_discount_for_consumer

    consumer_object = models.UserInfo.objects.filter(name=out_game_token.name).first()
    print('out_phone_charge.name', out_game_token.name)
    print('consumer_object:::', consumer_object)
    consumer_object.account -= out_game_token.denomination * game_discount_for_consumer
    consumer_object.save()
    game_data_out(
        out_game_token.denomination,
        out_game_token.consumer,
        out_game_token.in_storage_person,
        out_game_token.out_storage_person)

    return redirect('/game/list/')


def game_out_reout(request,uid):
    """将 Out_GameTokens 的记录流转回 GameTokens"""
    out_game_token = Out_GameTokens.objects.get(id=uid)

    # 创建新的 GameTokens 实例并保存
    game_token = GameTokens.objects.create(
        name = out_game_token.name,
        game_name=out_game_token.game_name,
        denomination=out_game_token.denomination,
        charge_link=out_game_token.charge_link,
        order_create_time=out_game_token.order_create_time,
        consumer=out_game_token.consumer,
        in_storage_person=request.session['info']['name'],  # 指定新的入库人
        order_number=out_game_token.order_number,  # 保持订单号不变
    )
    out_game_token.delete()

    # 将客户的账户余额更新
    if request.user.usertype == 2:
        game_discount_for_consumer = models.Discount.objects.filter(name=request.user.name).first().game_discount_for_consumer

    if request.user.usertype in [4, 5]:
        creater_user = models.UserInfo.objects.filter(name=request.user.name).first().create_person
        game_discount_for_consumer = models.Discount.objects.filter(name=creater_user).first().game_discount_for_consumer

    consumer_object = models.UserInfo.objects.filter(name=out_game_token.name).first()
    print('out_phone_charge.name', out_game_token.name)
    print('consumer_object:::', consumer_object)
    consumer_object.account += out_game_token.denomination * game_discount_for_consumer
    consumer_object.save()
    game_data_reout(
        out_game_token.denomination,
        out_game_token.consumer,
        out_game_token.in_storage_person,
        out_game_token.out_storage_person)

    return redirect('/game/out/list/')


def game_out_list(request):
    if request.user.usertype in [1, 2, 4, 5]:
        queryset = models.Out_GameTokens.objects.all()
        print(queryset)
    elif request.user.usertype == 3:
        queryset = models.Out_GameTokens.objects.filter(consumer=request.user.name)
        print(queryset)

    return render(request,'game_list.html',{'queryset':queryset})


def phone_list(request):
    if request.user.usertype in [1, 2, 4, 5]:
        queryset = models.PhoneCharge.objects.all()
        print(queryset)
    elif request.user.usertype == 3:
        queryset = models.PhoneCharge.objects.filter(consumer=request.user.name)
        print(queryset)
    return render(request,'phone_list.html',{'queryset':queryset})

class PhoneModelForm(BootstrapModelForm):
    class Meta:
        model = models.PhoneCharge
        fields = ['operator','denomination','phonenumber','consumer']

def phone_add(request):
    title = '添加话费订单'
    if request.method == 'GET':

        form = PhoneModelForm()
        if request.user.usertype == 3:  # 消费者的用户类型标识为 3
            form.fields.pop('consumer')
        context = {
            'form':form,
            'title':title
        }
        return render(request,'phone_add.html',context)

    form = PhoneModelForm(data=request.POST)
    if request.user.usertype == 3:  # 消费者的用户类型标识为 3
        form.fields.pop('consumer')
    if form.is_valid():
        create_person = request.session['info']['name']
        form.instance.in_storage_person = create_person
        form.instance.order_number = generate_order_id()
        #设置消费者的名字
        if request.user.usertype == 3:
            form.instance.name = request.user.name
            form.instance.consumer = request.user.name
        else:
            form.instance.name = form.cleaned_data['consumer']

        form.save()
        return redirect('/phone/list/')

    return render(request, 'phone_add.html', {'form': form})

def phone_edit(request,uid):
    title = '编辑话费订单'
    row_object = models.PhoneCharge.objects.filter(id=uid).first()
    if request.method == 'GET':
        form = PhoneModelForm(instance=row_object)
        context = {
            'form': form,
            'title': title
        }
        return render(request,'phone_add.html',context)

    form = PhoneModelForm(data=request.POST,instance=row_object)
    form.save()
    return redirect('/phone/list/')




def phone_delete(request,uid):
    models.PhoneCharge.objects.filter(id=uid).delete()
    return redirect('/phone/list/')



def phone_out(request,uid):

    #获取当前点击出库的这个列表的实例
    phonecharge_object = PhoneCharge.objects.get(id=uid)
    #获取当前消费者名称
    consumer_name = phonecharge_object.consumer


    print('phonecharge_object:',phonecharge_object)
    print('phonecharge_object.name:', phonecharge_object.name)

    # 将phonecharge的每个必须要求有数值的字段，全部转录到出库表中，创建新的 Out_PhoneCharge 实例并保存
    out_phone_charge = Out_PhoneCharge(

        name = phonecharge_object.name,
        operator=phonecharge_object.operator,
        denomination=phonecharge_object.denomination,
        phonenumber=phonecharge_object.phonenumber,
        order_create_time=phonecharge_object.order_create_time,
        consumer=phonecharge_object.consumer,
        in_storage_person=phonecharge_object.in_storage_person,
        order_number=phonecharge_object.order_number,
        order_finish_time=datetime.datetime.now().date(),  # 当前时间
        order_status=1,  # 默认状态：已支付
        out_storage_person= request.user.name,  # 点击出库的人
    )

    # 保存新创建的 Out_PhoneCharge 实例
    out_phone_charge.save()

    #将消费者的账户余额更新
    #获取订单消费者对应的管理员所设置的折扣系数
    #如果当前登录用户为管理员   【此处假设仅为其直属管理员】
    if request.user.usertype == 2:
        phone_discount_for_consumer = models.Discount.objects.filter(name=request.user.name).first().phone_discount_for_consumer
    #如果当前登录的用户为消费者直属管理员所创建的供应商或者客服
    if request.user.usertype in [4,5]:
        #首先找到当前登录用户的创建者，即直属管理员
        creater_user = models.UserInfo.objects.filter(name=request.user.name).first().create_person
        #获取当前登录用户直属管理员设置的折扣系数
        phone_discount_for_consumer = models.Discount.objects.filter(name=creater_user).first().phone_discount_for_consumer

    #获取当前消费者对象
    consumer_object = models.UserInfo.objects.filter(name=consumer_name).first()
    # print('out_phone_charge.name',out_phone_charge.name)
    # print('consumer_object:::',consumer_object)
    #获取当前消费者对象的账户余额 并减去出库面值*折扣系数  然后自动更新余额
    consumer_object.account -= out_phone_charge.denomination * phone_discount_for_consumer
    #将更新的余额，保存，即持久化到数据库
    consumer_object.save()

    #分别获取当前消费者，当前登录者，入库人，出库人所属的团体

    #判断当前登录的人
    if request.user.usertype == 2:
        admin_name = request.user.name
    if request.user.usertype in [3,4,5]:
        user_object = models.UserInfo.objects.filter(name=request.user.name).first()
        user_name = user_object.name
        admin_name = user_object.create_person

    #判断入库人
    in_storage_object = models.UserInfo.objects.filter(name=out_phone_charge.in_storage_person).first()
    if in_storage_object.usertype == 2:
        in_storage_of_admin_name = in_storage_object.name
    if in_storage_object.usertype in [3]:
        in_storage_of_admin_name = in_storage_object.create_person

    #判断出库人
    out_storage_object = models.UserInfo.objects.filter(name=out_phone_charge.out_storage_person).first()
    if out_storage_object.usertype == 2:
        out_storage_of_admin_name = out_storage_object.name
    if out_storage_object.usertype in [4, 5]:
        out_storage_of_admin_name = out_storage_object.create_person
        if out_storage_object.usertype == 4:
            #获取当前供过货的直属管理员为其创建的折扣系数
            #phone_discount_for_vendor = models.Discount.objects.filter(name=out_storage_of_admin_name).first().phone_discount_for_vendor   #这一行是可以正常工作的，但是我总觉得，这样在discount中添加name，是不专业，也不灵活。万一修改了客户的名称，此处无法同步
            phone_discount_for_vendor = models.Discount.objects.filter(userinfo__name=out_storage_of_admin_name).first().phone_discount_for_vendor
            out_storage_object_data, created = Data.objects.get_or_create(name=out_storage_object.name)
            out_storage_object_data.vendor_currency += out_phone_charge.denomination * phone_discount_for_vendor
            out_storage_object_data.save()

    #判断消费者
    if consumer_object.usertype == 2:
        consumer_of_admin_name = consumer_object.name
    if consumer_object.usertype in [3]:
        consumer_of_admin_name = consumer_object.create_person

    print('进入之前的幻想')
    #更新Data模型中关于phone的相关字段及公共计数字段
    phone_data_out(
        out_phone_charge.denomination,       #订单的面值
        out_phone_charge.consumer,           #消费者的名称
        # out_phone_charge.in_storage_person,  #入库人
        # out_phone_charge.out_storage_person, #出库人
        admin_name,
        in_storage_of_admin_name,
        out_storage_of_admin_name,
        consumer_of_admin_name,

        out_storage_object,

    )



    # 删除原始 PhoneCharge 记录
    phonecharge_object.delete()

    return redirect('/phone/list/')  # 重新定向到列表页或其他页面



def phone_out_reout(request,uid):

    out_phone_charge = Out_PhoneCharge.objects.get(id=uid)

    # 创建新的 PhoneCharge 实例并保存
    phone_charge = PhoneCharge.objects.create(
        userinfo=models.UserInfo.objects.filter(name=request.user.name).first(),
        name = out_phone_charge.name,
        operator=out_phone_charge.operator,
        denomination=out_phone_charge.denomination,
        phonenumber=out_phone_charge.phonenumber,
        order_create_time=out_phone_charge.order_create_time,
        consumer=out_phone_charge.consumer,
        in_storage_person=request.session['info']['name'],  # 指定新的入库人
        order_number=out_phone_charge.order_number,  # 保持订单号不变
    )

    # 删除原始的 Out_PhoneCharge 记录
    out_phone_charge.delete()


    # 将客户的账户余额更新
    if request.user.usertype == 2:
        phone_discount_for_consumer = models.Discount.objects.filter(name=request.user.name).first().phone_discount_for_consumer

    if request.user.usertype in [4, 5]:
        creater_user = models.UserInfo.objects.filter(name=request.user.name).first().create_person
        phone_discount_for_consumer = models.Discount.objects.filter(name=creater_user).first().phone_discount_for_consumer

    consumer_object = models.UserInfo.objects.filter(name=out_phone_charge.name).first()
    print('out_phone_charge.name', out_phone_charge.name)
    print('consumer_object:::', consumer_object)
    consumer_object.account += out_phone_charge.denomination * phone_discount_for_consumer
    consumer_object.save()
    phone_data_reout(
        out_phone_charge.denomination,
        out_phone_charge.consumer,
        out_phone_charge.in_storage_person,
        out_phone_charge.out_storage_person)

    return redirect('/phone/out/list/')  # 重新定向到列表页或其他页面

def phone_out_list(request):
    if request.user.usertype in [1, 2, 4, 5]:
        queryset = models.Out_PhoneCharge.objects.all()
        print(queryset)
    elif request.user.usertype == 3:
        queryset = models.Out_PhoneCharge.objects.filter(consumer=request.user.name)
        print(queryset)

    return render(request,'phone_list.html',{'queryset':queryset})



def user_list(request):
    if request.user.usertype != 1:
        queryset = models.UserInfo.objects.filter(usertype__in=[3,4,5])
        return render(request,'user_list.html',{'queryset':queryset})
    queryset = models.UserInfo.objects.all()
    return render(request, 'user_list.html', {'queryset': queryset})


class UserModeForm(BootstrapModelForm):

    class Meta:
        model = models.UserInfo
        exclude = ['create_person']

    def __init__(self, *args, **kwargs):
        # 获取当前用户类型并传递给表单
        current_user_type = kwargs.pop('current_user_type', None)
        super().__init__(*args, **kwargs)

        # 如果是管理员，限制用户类型只能选择消费者或供应商
        if current_user_type == 2:
            self.fields['usertype'].queryset = UserInfo.objects.filter(usertype__in=[3, 4,5])  # 只允许选择消费者和供应商
        # 如果是超级管理员，不做限制
        elif current_user_type == 1:
            self.fields['usertype'].queryset = UserInfo.objects.all()  # 允许选择所有类型

    def clean_name(self):
        name = self.cleaned_data['name']
        # 在编辑用户时，当前对象会保留实例的 id
        if self.instance.pk:
            # 如果是编辑，排除当前对象的 pk
            if UserInfo.objects.filter(name=name).exclude(pk=self.instance.pk).exists():
                raise forms.ValidationError("用户名已存在，请选择其他用户名")

        else:
            exists = models.UserInfo.objects.filter(name=name).exists()
            if exists:
                raise ValidationError('用户名已存在，请使用其他用户名')
        return name



def user_add(request):
    #POST和GET的 基础通用信息
    title = '添加用户'
    create_person = request.session['info']['name']
    current_user_type = request.user.usertype
    print('当前用户类型',current_user_type)

    if request.method == 'GET':
        form = UserModeForm(current_user_type=current_user_type)
        print('form:',form.fields['usertype'].queryset)
        if current_user_type == 2:
#usertype__in=[3, 4] 是一个过滤条件，意思是筛选出 usertype 字段值为 3 或 4 的 UserInfo 对象。__in 是 Django ORM 的一种查找方式，表示字段值在某个列表中的记录。
            form.fields['usertype'].queryset = UserInfo.objects.filter(usertype__in=[3, 4,5])
        context = {
            'form':form,
            'title':title
        }
        return render(request,'user_add.html',context)

    #以下是POST提交时的函数代码
    form = UserModeForm(data=request.POST,current_user_type=current_user_type)
    if form.is_valid():
        form.instance.create_person = create_person
        if current_user_type == 2:
            #被创建的用户的用户类型
            user_type = form.cleaned_data['usertype']
            if user_type not in [3, 4,5]:
                return HttpResponseForbidden("你没有权限创建该类型的用户")


        form.save()
        #同时为被创建的用户初始化Data模块的数据
        Data.objects.create(
            name = form.cleaned_data['name'],
            #usertype = form.cleaned_data['usertype'],
            # account= form.cleaned_data['account'],
            userinfo= models.UserInfo.objects.filter(name=form.cleaned_data['name']).first(),
        )

        # 当且仅当被创建用户类型为管理员，即2，为其初始化折扣相关的模型
        if form.cleaned_data['usertype'] == 2:
            models.Discount.objects.create(
                name = form.cleaned_data['name'],
                userinfo = models.UserInfo.objects.filter(name=form.cleaned_data['name']).first(),
            )
        print('heihei',form.fields['name'])
        return redirect('/user/list')
    else:
        #用户名重复或者错误时提交跳转的页面
        return render(request, 'user_add.html', {'form': form})


def user_edit(request,uid):
    title = '编辑用户'
    row_object = models.UserInfo.objects.filter(id=uid).first()
    if request.method == 'GET':
        form = UserModeForm(instance=row_object)
        context = {
            'form': form,
            'title': title
        }
        return render(request,'user_add.html',context)

    form = UserModeForm(request.POST,instance = row_object)
    # print(row_object)
    # print(row_object.name)
    if form.is_valid():
        form.save()
        # 如果将用户修改权限为管理员，即2，为其初始化折扣相关的模型   eg：由消费者修改为管理员
        if form.cleaned_data['usertype'] == 2:
            models.Discount.objects.create(
                name=form.cleaned_data['name'],
                userinfo=models.UserInfo.objects.filter(name=form.cleaned_data['name']).first(),
            )
            return redirect('/user/list/')
        return redirect('/user/list/')
    # print(form.errors)
    # return HttpResponse('cuowu')
    return render(request, 'user_add.html', {'form': form})


def user_delete(request,uid):
    models.UserInfo.objects.filter(id=uid).delete()
    return redirect('/user/list/')


def dashboard_single(request):

    user_data_object = models.Data.objects.filter(name=request.user.name).first()
    print(user_data_object)

    context = {
        'user_data_object':user_data_object,
    }

    return render(request,'dashboard_single.html',context)


def dashboard_multiple(request):

    #查询所有由当前登录者创建的消费者的数据信息
    queryset_consumer = models.Data.objects.filter(userinfo__create_person=request.user.name,userinfo__usertype=3)

    # 查询所有由当前登录者创建的供应商的数据信息
    queryset_vendor = models.Data.objects.filter(userinfo__create_person=request.user.name, userinfo__usertype=4)

    # 查询所有由当前登录者创建的客服的数据信息
    queryset_kefu = models.Data.objects.filter(userinfo__create_person=request.user.name, userinfo__usertype=5)

    # queryset_admin = models.Data.objects.filter(
    #     #通过外键，查找入库人，如果入库人是当前登录的管理员或者入库人是由当前登录的管理员创建的
    #     Q(out_phonecharge__in_storage_person=request.user.name)|Q(out_phonecharge__userinfo__create_person=request.user.name)
    #     &
    #     # 通过外键，查找出库人，如果出库人是不是当前登录的管理员或者出库人不是由当前登录的管理员创建的
    #     (~Q(out_phonecharge__out_storage_person =request.user.name)|~Q(out_phonecharge__userinfo__create_person= request.user.name))
    # )
    queryset_admin = models.Data.objects.filter(Q(userinfo__usertype=2)&~Q(userinfo__name = request.user.name))
    print('queryset_admin',queryset_admin)

    context = {
        'queryset_consumer': queryset_consumer,
        'queryset_vendor':queryset_vendor,
        'queryset_kefu':queryset_kefu,
        'queryset_admin':queryset_admin,
    }

    return render(request,'dashboard_multiple.html',context)


@csrf_exempt  # 仅用于调试阶段，生产环境中需要启用 CSRF
def set_phone_discount_for_consumer(request):
    if request.method == 'POST':
        try:
            # 获取 AJAX 传递的参数
            discount = request.POST.get('discount')

            # 校验折扣值是否合法
            if not discount or float(discount) <= 0:
                return JsonResponse({'message': '折扣值必须大于 0'}, status=400)

            # 更新数据库
            discount_value = float(discount)
            models.Discount.objects.update(phone_discount_for_consumer=discount_value)  # 更新所有记录

            # 返回成功消息
            return JsonResponse({'message': f'话费折扣设置为 {discount_value}'})
        except Exception as e:
            # 捕获异常并返回错误
            return JsonResponse({'message': f'发生错误：{str(e)}'}, status=500)

    return JsonResponse({'message': '仅支持 POST 请求'}, status=405)


@csrf_exempt  # 仅用于调试阶段，生产环境中需要启用 CSRF
def set_game_discount_for_consumer(request):
    if request.method == 'POST':
        try:
            # 获取 AJAX 传递的参数
            discount = request.POST.get('discount')

            # 校验折扣值是否合法
            if not discount or float(discount) <= 0:
                return JsonResponse({'message': '折扣值必须大于 0'}, status=400)

            # 更新数据库
            discount_value = float(discount)
            models.Discount.objects.update(game_discount_for_consumer=discount_value)  # 更新所有记录

            # 返回成功消息
            return JsonResponse({'message': f'点券折扣设置为 {discount_value}'})
        except Exception as e:
            # 捕获异常并返回错误
            return JsonResponse({'message': f'发生错误：{str(e)}'}, status=500)

    return JsonResponse({'message': '仅支持 POST 请求'}, status=405)



@csrf_exempt  # 仅用于调试阶段，生产环境中需要启用 CSRF
def set_phone_discount_for_vendor(request):
    if request.method == 'POST':
        try:
            # 获取 AJAX 传递的参数
            discount = request.POST.get('discount')

            # 校验折扣值是否合法
            if not discount or float(discount) <= 0:
                return JsonResponse({'message': '折扣值必须大于 0'}, status=400)

            # 更新数据库
            discount_value = float(discount)
            models.Discount.objects.update(phone_discount_for_vendor=discount_value)  # 更新所有记录

            # 返回成功消息
            return JsonResponse({'message': f'话费折扣设置为 {discount_value}'})
        except Exception as e:
            # 捕获异常并返回错误
            return JsonResponse({'message': f'发生错误：{str(e)}'}, status=500)

    return JsonResponse({'message': '仅支持 POST 请求'}, status=405)


@csrf_exempt  # 仅用于调试阶段，生产环境中需要启用 CSRF
def set_game_discount_for_vendor(request):
    if request.method == 'POST':
        try:
            # 获取 AJAX 传递的参数
            discount = request.POST.get('discount')

            # 校验折扣值是否合法
            if not discount or float(discount) <= 0:
                return JsonResponse({'message': '折扣值必须大于 0'}, status=400)

            # 更新数据库
            discount_value = float(discount)
            models.Discount.objects.update(game_discount_for_vendor=discount_value)  # 更新所有记录

            # 返回成功消息
            return JsonResponse({'message': f'点券折扣设置为 {discount_value}'})
        except Exception as e:
            # 捕获异常并返回错误
            return JsonResponse({'message': f'发生错误：{str(e)}'}, status=500)

    return JsonResponse({'message': '仅支持 POST 请求'}, status=405)



def e(request):
    # other_in_my_out_gameout_num = models.Out_GameTokens.objects.filter(
    #     Q(in_storage_person__ne = request.user.name)&Q(out_storage_person=request.user.name))
    #
    # my_in_my_out_gameout_num = models.Out_GameTokens.objects.filter(
    #     in_storage_person=request.user.name,out_storage_person=request.user.name)
    #
    # other_in_my_out_phoneout_num = models.Out_PhoneCharge.objects.filter(
    #     Q(in_storage_person__ne=request.user.name) & Q(out_storage_person=request.user.name))
    #
    # my_in_my_out_phoneout_num = models.Out_PhoneCharge.objects.filter(
    #     in_storage_person=request.user.name, out_storage_person=request.user.name)
    #
    # total_num = other_in_my_out_phoneout_num + other_in_my_out_phoneout_num + my_in_my_out_phoneout_num + my_in_my_out_gameout_num

    # admin_queryset = UserInfo.objects.filter(usertype__in=[2])
    # customer_queryset = UserInfo.objects.filter(usertype__in=[3])
    # vendor_queryset = UserInfo.objects.filter(usertype__in=[4])
    # kefu_queryset = UserInfo.objects.filter(usertype__in=[5])

    if request.user.usertype == 1:
        huafei_liushui = models.Out_PhoneCharge.objects.filter(order_status=1).aggregate(total=Sum('denomination'))['total'] or 0
        game_liushui = models.Out_GameTokens.objects.filter(order_status=1).aggregate(total=Sum('denomination'))['total'] or 0
        total_liushui = huafei_liushui + game_liushui

        #管理员小猫的相关数据
        #1.由小猫本人出库的订单数
        game_num_小猫 = models.Out_GameTokens.objects.filter(out_storage_person='小猫').count()
        huafei_num_小猫 = models.Out_PhoneCharge.objects.filter(out_storage_person='小猫').count()
        total_num = game_num_小猫 + huafei_num_小猫

        #2.查询由小猫创建的供应商和客服有哪些人，并形成结果集
        #2.1查询由小猫创建的供应商有哪些
        users_供应商 = models.UserInfo.objects.filter(usertype=4, create_person='小猫')
        #2.2查询由小猫创建的客服有哪些
        users_客服 = models.UserInfo.objects.filter(usertype=5, create_person='小猫')
        #2.3查询由小猫创建的供应商和客服的集合
        users = models.UserInfo.objects.filter(Q(usertype=4) | Q(usertype=5),create_person='小猫')
        print('查询的users',users)

        #3.查询由小猫创建的供应商和客服分别处理了点券和话费订单有多少
        #3.1获取由小猫创建的供应商出库的订单数
        # 3.1.1获取由小猫创建的供应商产生的Out_GameTokens 记录
        game_tokens_供应商 = models.Out_GameTokens.objects.filter(out_storage_person__in=users_供应商).count()
        # 3.1.2获取由小猫创建的供应商产生的PhoneCharge 记录
        phone_charge_供应商 = models.Out_PhoneCharge.objects.filter(out_storage_person__in=users_供应商).count()

        # 3.2获取由小猫创建的客服出库的订单数
        # 3.2.1获取由小猫创建的客服产生的Out_GameTokens 记录
        game_tokens_客服 = models.Out_GameTokens.objects.filter(out_storage_person__in=users_客服).count()
        # 3.2.2获取由小猫创建的供应商产生的PhoneCharge 记录
        phone_charge_客服 = models.Out_PhoneCharge.objects.filter(out_storage_person__in=users_客服).count()


        #3.3获取由小猫创建的供应商，客服合计产生的Out_GameTokens记录和PhoneCharge记录
        #3.3.1获取由小猫创建的供应商，客服合计产生的Out_GameTokens 记录
        game_tokens_供应商和客服 = models.Out_GameTokens.objects.filter(out_storage_person__in=users).count()
        #3.3.2获取由小猫创建的供应商，客服合计产生的PhoneCharge 记录
        phone_charge_供应商和客服 = models.Out_PhoneCharge.objects.filter(out_storage_person__in=users).count()



        context = {
            'game_tokens_供应商':game_tokens_供应商,
            'phone_charge_供应商':phone_charge_供应商,
            'total_供应商':game_tokens_供应商 + phone_charge_供应商,

            'game_tokens_客服':game_tokens_客服,
            'phone_charge_客服':phone_charge_客服,
            'total_客服':game_tokens_客服 + phone_charge_客服,

            'game_tokens_供应商和客服':game_tokens_供应商和客服,
            'phone_charge_供应商和客服':phone_charge_供应商和客服,
            'total_供应商和客服':game_tokens_供应商和客服 + phone_charge_供应商和客服,

            'total_liushui': total_liushui,
            'game_num_小猫': game_num_小猫,
            'huafei_num_小猫': huafei_num_小猫,
            'total_num': total_num,


        }
        return render(request, 'dashboard_single.html', context)

    return render(request, 'dashboard_single.html')





